#include "mesh_loader.h"
#define TINYOBJLOADER_IMPLEMENTATION
#include <tiny_obj_loader.h>

namespace vkrender
{
	bool MeshLoader::load_from_file(const std::string& filepath)
	{
		vertices.clear();
		indices.clear();

		tinyobj::attrib_t attrib;
		std::vector<tinyobj::shape_t> shapes;
		std::vector<tinyobj::material_t> materials;

		std::string warn, err;
		if (!tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, filepath.c_str()))
		{
			std::cout << "failed to load model from " << filepath << std::endl;
			return false;
		}
		
		// std::unordered_map<MeshVertex, uint32_t> uniqueVertices;
		uint32_t vindex = 0;
		for (const auto& shape : shapes)
		{
			for (const auto& index : shape.mesh.indices)
			{
				MeshVertex vertex;
				vertex.position = {
					attrib.vertices[3 * index.vertex_index + 0],
					attrib.vertices[3 * index.vertex_index + 1],
					attrib.vertices[3 * index.vertex_index + 2],
				};
				vertex.texcoords = {
					attrib.texcoords[2 * index.texcoord_index + 0],
					1.0f - attrib.texcoords[2 * index.texcoord_index + 1]
				};
				vertex.color = { 1.0f, 1.0f, 1.0f };
				vertices.push_back(vertex);

				indices.push_back(vindex);
				vindex += 1;
			}
		}
		return true;
	}
}
